
package cc.yiueil.service;

import cc.yiueil.model.dto.UserLoginDTO;
import cc.yiueil.model.entity.UserEntity;
import cc.yiueil.model.entity.UserPrincipalEntity;
import cc.yiueil.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.security.Security;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    public String authorize(UserLoginDTO userLoginDTO) {
        String uname = userLoginDTO.getUname();
        String pwd = userLoginDTO.getPwd();
        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(uname, pwd);
        // 这里的authenticate就是实际的授权结果
        Authentication authenticate = authenticationManager.authenticate(authRequest);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        UserPrincipalEntity userPrincipal = (UserPrincipalEntity) authenticate.getPrincipal();
        UserEntity userEntity = userPrincipal.getUserEntity();
        String subject = "user:" + userEntity.getId();
        int expireMillisecond = 5 * 60 * 1000;
        redisTemplate.opsForValue().set(subject, userEntity, expireMillisecond, TimeUnit.MILLISECONDS);
        return JwtUtils.generateIdToken(subject, expireMillisecond);
    }

    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserEntity userEntity = (UserEntity) authentication.getPrincipal();
        redisTemplate.opsForValue().getAndDelete("user:" + userEntity.getId());
    }
}
